<?php

namespace app\admin\model;

use app\common\model\DiamondLog;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\pay\Order;
use app\common\model\ScoreLog;
use app\common\model\user\Club;
use app\common\model\user\Withdraw;
use think\Exception;
use think\Model;
use function fast\e;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text',
        'parent_text',
        'parent_num',
        'topup',
        'withdraw_gold',
        'withdraw_diamond'
    ];

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            $origin = $row->getOriginData();

            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }

            if (isset($changed['parent_id'])) {
                if ($changed['parent_id']) {
                    if ($changed['parent_id'] == $origin['parent_id']) {
                        throw new Exception("不能自己邀请自己");
                    }
                    $parent_id = self::where('id', $changed['parent_id'])->value('parent_id');
                    if ($parent_id == $row->id) {
                        throw new Exception("你已经是该用户上级");
                    }
                }
            }

            if (isset($changed['real_name']) || isset($changed['card_num'])) {
                $real_name = isset($changed['real_name']) ? $changed['real_name'] : $origin['real_name'];
                $card_num = isset($changed['card_num']) ? $changed['card_num'] : $origin['card_num'];

                if (!empty($real_name) || !empty($card_num)) {
                    $exist = self::where('card_num', $card_num)->where('id', '<>', $row->id)->find();
                    if ($exist) {
                        throw new \Exception("当前身份信息已存在");
                    }
                    $result = self::yanzheng($card_num, $real_name);
                    if ($result['respCode'] == "000") {
                        $row->real_name = $real_name;
                        $row->card_num = $card_num;
                        $row->real_status = 1;
                    } else {
                        $msg = isset($result) ? $result['respMessage'] : "身份验证信息有误";
                        throw new \Exception($msg);
                    }
                }
            }

            if (isset($changed['is_club'])) {
                if ($changed['is_club'] == 1) {
                    $row->club_time = time();

                    $club = Club::where(['user_id' => $row['id']])->find();
                    if (!$club) {
                        Club::create([
                            'user_id' => $row['id'],
                        ]);
                    }
                }
            }

            if (isset($changed['club_id'])) {
                if ($changed['club_id'] == 4) {
                    $count = self::where('club_id', 4)->count();
                    if ($count > 0) {
                        throw new Exception("当前身份限制一位");
                    }
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
            if (isset($changedata['diamond']) && (int)$changedata['diamond'] !== (int)$origin['diamond']) {
                DiamondLog::create(['user_id' => $row['id'], 'diamond' => $changedata['diamond'] - $origin['diamond'], 'before' => $origin['diamond'], 'after' => $changedata['diamond'], 'memo' => '管理员变更钻石']);
            }
            if (isset($changedata['gold']) && (int)$changedata['gold'] !== (int)$origin['gold']) {
                GoldLog::create(['user_id' => $row['id'], 'gold' => $changedata['gold'] - $origin['gold'], 'before' => $origin['gold'], 'after' => $changedata['gold'], 'memo' => '管理员变更金币']);
            }

        });
    }

    public function getOriginData()
    {
        return $this->origin;
    }

    public static function yanzheng($idNo, $name)
    {
        $host = "https://idenauthen.market.alicloudapi.com";
        $path = "/idenAuthentication";
        $method = "POST";
        $appcode = "3e71106a601e4da38732bbbc27015138";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "idNo={$idNo}&name={$name}";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $result = curl_exec($curl);
        return json_decode($result, true);
    }

    public function getTopupAttr($value, $data)
    {
        return Order::where('user_id', $data['id'])->where('status', 1)->sum('price');
    }

    public function getWithdrawGoldAttr($value, $data)
    {
        return Withdraw::where("user_id", $data['id'])->where('status', 1)->where('type', 1)->sum('price');
    }

    public function getWithdrawDiamondAttr($value, $data)
    {
        return Withdraw::where("user_id", $data['id'])->where('status', 1)->where('type', 2)->sum('price');
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getCurrencyList()
    {
        return ["money" => "银币", "score" => "积分", "diamond" => "钻石", "gold" => "金币"];
    }

    public function getParentTextAttr($value, $data)
    {
        return $this->where('id', $data['parent_id'])->value('mobile', "无邀请人");
    }

    public function getParentNumAttr($value, $data)
    {
        return $this->where('parent_id', $data['id'])->count();
    }

    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function club()
    {

        return $this->belongsTo('app\common\model\Club', 'club_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function vip()
    {
        return $this->belongsTo('app\common\model\user\Viptype', 'vip_type_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

}
